package com.qch.demo_01;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @Author qch
 * @Date 2021/8/3
 */
public class CompletableFutureDemo7AllOf {
    private static final Random RANDOM=new Random();
    private static volatile  int result=0;

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture[] futures = new CompletableFuture[10];
        for (int i = 0; i < 10; i++) {
            CompletableFuture<Void> future = CompletableFuture.runAsync(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000 + RANDOM.nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    result++;
                }
            });
            futures[i]=future;

        }
//        for (int i = 0; i < 10; i++) {
//         futures[i].get();
//            System.out.println(result);
//        }
        //等所有结束
//        CompletableFuture.allOf(futures).thenRun(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println("计算完成");
//            }
//        }).get();
        //  System.out.println(result);
        CompletableFuture.anyOf(futures).thenRun(new Runnable() {
            @Override
            public void run() {
                System.out.println(result);
            }
        }).get();

    }
}